<template>
  <div>
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/exam/examManage' }">考试</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="subjectTitle">
      <el-collapse style="margin-left: 5%;" v-model="activeNames" @change="handleChange">
        <el-collapse-item title="筛选考试" name="1">
          <div class="check-box">科目：
            <el-radio-group v-model="searchForm.subjectId">
              <el-radio v-for="item in subjects"
                        :key="item.id"
                        :label="item.id">{{item.name}}</el-radio>
            </el-radio-group>
          </div>
          <div class="check-box">考试状态：
            <el-radio-group v-model="searchForm.status">
              <el-radio label="未发布">未发布</el-radio>
              <el-radio label="未开始">未开始</el-radio>
              <el-radio label="进行中">进行中</el-radio>
              <el-radio label="已结束">已结束</el-radio>
            </el-radio-group>
          </div>
          <el-link type="info" @click="clearSearch">清空</el-link>
        </el-collapse-item>
      </el-collapse>
      <el-button type="primary" style="margin-left:10%; height: 50px;" @click="search">搜索考试</el-button>
      <el-button type="primary" style="margin-left:10%; height: 50px;" @click="addDialogVisible = true">增加考试</el-button>
    </div>
    <div style="width: 90%; margin-left: 5%; margin-top: 10px;">
      <el-table
        :data="examList"
        style="width: 100%">
        <el-table-column
          prop="name"
          label="名称">
        </el-table-column>
        <el-table-column
          prop="subject"
          label="科目"
          width="130">
        </el-table-column>
        <el-table-column
          prop="status"
          label="考试状态"
          width="130">
        </el-table-column>
        <el-table-column
          label="开始时间"
          prop="startTime"
          width="180">
        </el-table-column>
        <el-table-column
          label="结束时间"
          prop="endTime"
          width="180">
        </el-table-column>
        <el-table-column
          label="操作"
          width="180">
          <template slot-scope="scope" style="display: grid; grid-template-columns: 50% 50%">
            <el-link type="info" @click="goToExam(scope.row)">查看详情</el-link>
            <el-link type="danger" @click="deleteExam(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          layout="total, prev, pager, next"
          :page-size="pagination.page_size"
          :current-page="pagination.index"
          :total="pagination.total"
          @current-change="changePage">
        </el-pagination>
      </div>
    </div>
<!--  增加考试  -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="30%"
      center>
      <el-form label-width="80px" :model="addForm" ref="addForm">
        <el-form-item label="考试名称">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="考试科目">
          <el-select v-model="addForm.subjectId" placeholder="请选择科目">
            <el-option
              :key="subject.id"
              v-for="subject in subjects"
              :label="subject.name"
              :value="subject.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="addForm.startTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="addForm.endTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addExam">确 定</el-button>
      </span>
    </el-dialog>

    <!--  删除考试  -->
    <el-dialog
      title="提示"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定删除考试吗，此操作无法撤销！</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="deleteConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {examSearchByTeacher, examAdd, examSearch, deleteExam} from '../../../api/exam'
import {findSubjectsByHouse} from '../../../api/questions'
export default {
  name: 'ExamManage',
  data () {
    return {
      // 删除考试
      deleteDialogVisible: false,
      // 分页信息
      pagination: {
        page_size: 5,
        index: 1,
        total: 0
      },
      // 筛选条件
      activeNames: [],
      searchForm: {
        subjectId: null,
        status: null
      },
      // 表格信息
      examList: [
        {
          createTime: '2022-04-02 15:54:34',
          endTime: '2022-04-03 04:00:00',
          id: 10,
          name: '2022软件工程考试',
          startTime: '2022-04-03 02:00:00',
          status: '未发布',
          subject: '软件工程',
          teacherNumber: '2019',
          updateTime: '2022-04-02 15:54:34'
        }
      ],
      // 增加考试
      addDialogVisible: false,
      addForm: {
        endTime: '',
        name: '',
        startTime: '',
        subjectId: null,
        teacherId: sessionStorage.getItem('teacherId')
      },
      subjects: [
        {
          id: 1,
          name: '静态科目'
        }
      ]
    }
  },
  mounted () {
    this.getSubjectByHouse()
    this.getExams()
  },
  methods: {
    // 查找该老师所有考试
    getExams () {
      let parameters = {
        teacherId: sessionStorage.getItem('teacherId'),
        page_size: this.pagination.page_size,
        index: this.pagination.index - 1
      }
      examSearchByTeacher(parameters).then(res => {
        console.log(res)
        if (res.data.errorCode === 0) {
          this.examList = res.data.data.list
          this.pagination.total = res.data.data.total
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 跳转详情
    goToExam (item) {
      this.$router.push({path: '/exam/examDetail', query: {exam: JSON.stringify(item)}})
    },
    // 增加考试
    addExam () {
      let that = this
      var flag = this.addForm.endTime !== '' &&
        this.addForm.name !== '' &&
        this.addForm.startTime !== '' &&
        this.addForm.subjectId !== null
      if (flag) {
        this.addForm.startTime = this.formatDate(this.addForm.startTime, 'yyyy-MM-ddThh:mm:ss.SSS')
        this.addForm.endTime = this.formatDate(this.addForm.endTime, 'yyyy-MM-ddThh:mm:ss.SSS')
        console.log(this.addForm)
        examAdd(this.addForm).then(res => {
          console.log(res)
          if (res.data.errorCode === 0) {
            that.$message.success('添加成功！')
            this.$refs['addForm'].resetFields()
            this.addDialogVisible = false
            this.getExams()
          } else {
            this.$message.error(res.data.message)
          }
        })
      } else {
        this.$message.error('请填写完整信息！')
      }
    },
    cancel () {
      this.$refs['addForm'].resetFields()
      this.addDialogVisible = false
    },
    // 通过学院获取科目
    getSubjectByHouse () {
      findSubjectsByHouse(sessionStorage.getItem('teacherHouse')).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.subjects = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 格式化日期
    formatDate (time, fmt) {
      const day = ['日', '一', '二', '三', '四', '五', '六']
      const o = {
        'M+': time.getMonth() + 1, // 月份
        'd+': time.getDate(), // 日
        'h+': time.getHours() - 8, // 小时
        'm+': time.getMinutes(), // 分
        's+': time.getSeconds(), // 秒
        'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
        'S+': time.getMilliseconds(), // 毫秒
        'D': time.getDay() // 星期
      }
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          const args = (k === 'S+') ? '000' : '00'
          let v = (args + o[k]).substr(('' + o[k]).length)
          if (k === 'D') {
            v = day[parseInt(v)]
          }
          fmt = fmt.replace(RegExp.$1, v)
        }
      }
      return fmt
    },
    // 翻页
    changePage (val) {
      this.pagination.index = val
      this.getExams()
    },
    // 搜索
    handleChange (val) {
      console.log(val)
    },
    // 搜索
    clearSearch () {
      this.searchForm = {
        subjectId: null,
        status: null
      }
      this.getExams()
    },
    search () {
      this.pagination = {
        page_size: 5,
        index: 1,
        total: 0
      }
      let parameters = {
        teacherId: sessionStorage.getItem('teacherId'),
        page_size: this.pagination.page_size,
        index: this.pagination.index - 1,
        subjectId: this.searchForm.subjectId,
        status: this.searchForm.status
      }
      examSearch(parameters).then(res => {
        console.log(res)
        if (res.data.errorCode === 0) {
          this.examList = res.data.data.list
          this.pagination.total = res.data.data.total
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 删除考试
    deleteExam (examId) {
      this.deleteDialogVisible = true
      this.deleteExamId = examId
    },
    deleteConfirm () {
      deleteExam({examId: this.deleteExamId, teacherNumber: sessionStorage.getItem('teacherNumber')}).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.$message.success('删除成功')
          this.deleteDialogVisible = false
          this.getExams()
        } else {
          this.$message.error(res.data.message)
        }
      })
    }
  }
}
</script>

<style scoped>
  .breadcrumb {
    padding: 20px;
  }

  .subjectTitle {
    font-size: 25px;
    font-weight: bold;
    margin: 0 20px;
    display: grid;
    grid-template-columns: 80% 10% 10%;
  }

  .check-box {
    margin-bottom: 5px;
    text-align: left;
  }
</style>
